package com.wbp.cms.web.controller.admin;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.wbp.cms.client.common.domain.OrganizationDO;
import com.wbp.cms.client.common.query.OrganizationQuery;
import com.wbp.cms.client.common.service.OrganizationService;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.user.domain.RoleDO;
import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.client.user.query.UserQuery;
import com.wbp.cms.client.user.service.RoleService;
import com.wbp.cms.client.user.service.UserService;
import com.wbp.cms.client.util.IdCardUtil;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.client.util.MD5Utils;
import com.wbp.cms.web.controller.BaseController;
import com.wbp.cms.web.util.SessionUtil;


/**
 * 用户管理
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月10日 下午4:54:28 
 */
@Controller("userMgrController")
@RequestMapping("/usermgr")
public class UserMgrController  extends BaseController{

   @Resource
   private  UserService  userService ;
   
   private static final Logger  logger = Logger.getLogger(UserMgrController.class) ;
   
   @Resource
   private RoleService  roleService ;
   
   @Resource
   private OrganizationService organizationService ;
   
   /**
    * 进入页面时的方法
    * @return
    */
   @RequestMapping("/tolist")
   public ModelAndView  toList(){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/user/userList"); 
     return mv ;
   }
   
   
   /**
    * 用户列表
    * @param pageNo
    * @param pageSize
    * @return
    */
  /* @RequestMapping("/list")
   public ModelAndView doList(  @RequestParam(value = "pageNo",
       required = false, defaultValue = "1") int pageNo,@RequestParam(value = "pageSize",
       required = false, defaultValue = "50") int pageSize) {

     ModelAndView mv = new ModelAndView();
     mv.setViewName("user/userList"); 
     
     UserQuery  userQuery =new UserQuery();
     userQuery.setPageNo(pageNo);
     userQuery.setPageSize(pageSize);
     
     Result<List<UserDO>> result = userService.queryUsers(userQuery) ;
     if(result.isSuccess() && result.getData()!=null &&  result.getData().size() > 0){
         mv.addObject("count", result.getTotal()) ;
         mv.addObject("userList", result.getData()) ;
     }
     return mv;
   }*/
   
   
   /**
    * 查询方法
    * @param userName
    * @param mobileNumber
    * @param realName
    * @param gender
    * @param customerLevel
    * @param pageNo
    * @param pageSize
    * @return
    */
   @RequestMapping(value="/query", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String doQuery(HttpServletRequest request , @RequestParam(value = "userName",
       required = false, defaultValue = "") String userName, @RequestParam(value = "mobileNumber",
       required = false, defaultValue = "") String mobileNumber,@RequestParam(value = "realName",
       required = false, defaultValue = "") String realName,@RequestParam(value = "gender",
       required = false, defaultValue = "0") int gender , @RequestParam(value = "start",
       required = false, defaultValue = "1") int start,@RequestParam(value = "length",
       required = false, defaultValue = "50") int pageSize) {

     Map<String,String> maps = this.getParameters(request) ;
     
     UserQuery  userQuery =new UserQuery();
     ///userQuery.setPageNo(pageNo);
     userQuery.setStart(start);
     userQuery.setPageSize(pageSize);
     if(StringUtils.isNotEmpty(userName))
       userQuery.setUserName(userName);
     if(StringUtils.isNotEmpty(mobileNumber))
       userQuery.setMobileNumber(mobileNumber); 
     if(StringUtils.isNotEmpty(realName))
       userQuery.setRealName(realName);
     if(gender >0)
       userQuery.setGender(gender);
     
     UserDO  user = SessionUtil.getCurrentUser(request.getSession() ) ;
     if(!this.isSuperUser(user.getUserName())){
        // userQuery.setCreator( user.getUserName() )  ;
         userQuery.setOrganizationId(user.getOrganizationId());
     }
     
     Result<List<UserDO>> result = userService.queryUsers(userQuery) ;
     return new Gson().toJson(getDataTableMapData(result,maps.get(DT_KEY_DRAW) )) ;
   }
   
   
   

   /**
    * to 修改密码页面
    * @param request
    * @return
    */
   @RequestMapping("/tomodifypwd")
   public ModelAndView  toModifyPwd(HttpServletRequest request,
                         @RequestParam(value="uid",required=true,defaultValue="0") Long uid){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/user/modifyPwd"); 
     
     if(uid !=null && uid>0){
       Result<UserDO> ur = this.userService.queryUserById(uid) ;
       if(ur.isSuccess())
           mv.addObject("user", ur.getData()) ;
     }
     return mv ;
   }
   
   /**
    * 修改密码页面
    * @param request
    * @return
    */
   @RequestMapping(value="/domodifypwd", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doModifyPwd(HttpServletRequest request  ){
     UserDO user = this.getRequestObject(request, UserDO.class) ;
     
     if(user == null || user.getId() == null || user.getId()<=0)
         return JsonUtils.toJson(Result.buildError("请刷新页面再修改密码")) ; 
     if(StringUtils.isEmpty(user.getOldPwd()))
         return JsonUtils.toJson(Result.buildError("请输入老密码")) ; 
     if(StringUtils.isEmpty(user.getPwd()))
         return JsonUtils.toJson(Result.buildError("请输入老密码")) ; 
     Result<UserDO>  ur = this.userService.queryUserById(user.getId()) ;
     if(ur.isFailed())
         return JsonUtils.toJson(Result.buildError("没有找到此用户")) ;
     try {
           String oldPwd = MD5Utils.strToMD5(user.getOldPwd()+ur.getData().getUserName()) ;
           if(ur.isSuccess() && !ur.getData().getPwd().equals(oldPwd))
             return JsonUtils.toJson(Result.buildError("旧密码错误,请重新输入")) ;
         
            user.setPwd(MD5Utils.strToMD5(user.getPwd()+ur.getData().getUserName()));
      } catch (UnsupportedEncodingException e) {
           logger.error("md5 error:",e);
      }
     Result<Boolean>  br = this.userService.modifyUser(user) ;
     if(br.isFailed())
       return JsonUtils.toJson(Result.buildError("修改密码失败")) ;
     
     return  JsonUtils.toJson(Result.buildSuccess(true)) ;
   }
     
     /**
      * 跳到新增客户页面
      * @param customerDO
      * @return
      */
     @RequestMapping("/toadd")
     public ModelAndView  toAddUser(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("admin/user/userAdd"); 
        UserDO  user =  SessionUtil.getCurrentUser(request.getSession()) ;
        setUserRole(request,mv,user) ;
        setChildOrganization(request,mv,user) ;
        
        mv.addObject("user_default_image_url", product_default_image_url) ; // default image
        
        return  mv ;
     }
   /**
    * 新增一条客户记录
    * @param customerDO
    * @return
    */
   @RequestMapping(value="/doadd", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doAdd(HttpServletRequest request  ){
     try{
       
        String params = this.getParameters(request).get("params") ;  
        if(params == null  || params.equals(""))
           return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        UserDO userDO = JsonUtils.toObject(params, UserDO.class) ;
       
         if(userDO == null )
           return JsonUtils.toJson(Result.buildError("参数不合法")) ;
         if(StringUtils.isEmpty(userDO.getUserName()))
           return JsonUtils.toJson(Result.buildError("用户名不能为空")) ;
         if(StringUtils.isEmpty(userDO.getPwd()))
           return JsonUtils.toJson(Result.buildError("用户密码不能为空")) ;
         userDO.setPwd( MD5Utils.strToMD5(userDO.getPwd() + userDO.getUserName()) ) ; 
         if(userDO.getIdCard() !=null && !userDO.getIdCard().equals("")){
           if(!IdCardUtil.verify(userDO.getIdCard()))
             return JsonUtils.toJson(Result.buildError("身份证号码不合法")) ;
        }
         UserDO  user = SessionUtil.getCurrentUser(request.getSession()) ;
         if(user == null){
             return JsonUtils.toJson(Result.buildError("请重新登录")) ;
         }
         userDO.setCreator(user.getUserName());
         
         Result<UserDO> ur = this.userService.queryUserByUserName(userDO.getUserName()) ;
         if(ur.isSuccess() && ur.getData()!=null)
             return JsonUtils.toJson(Result.buildError("已经存在此用户名称")) ;  
           
         Result<Long>  userResult =this.userService.addUser(userDO) ;
         
         return  JsonUtils.toJson(userResult,true) ;
     }catch(Throwable e){
       logger.error(BaseResultCode.USER_ADD_USER_ERROR.getErrMsg(), e);
       return JsonUtils.toJson(Result.buildError(BaseResultCode.USER_ADD_USER_ERROR));
     }
   }
   
   /**
    * 跳到 修改 客户页面
    * @param customerDO
    * @return
    */
   @RequestMapping("/toedit")
   public ModelAndView  toEdit(HttpServletRequest request,@RequestParam(value="userId",required=true,defaultValue="0") Long userId,
        @RequestParam(value="type",required=true,defaultValue="0") Integer type){
      ModelAndView mv = new ModelAndView();
      // mv.setViewName("user/userEdit"); 
      mv.setViewName("admin/user/userEdit"); 
      Result<UserDO>  result =  this.userService.queryUserById(userId);
      if(result.isSuccess()){
        UserDO u = result.getData() ;
        mv.addObject("user", u ) ;
        UserDO  user =  SessionUtil.getCurrentUser(request.getSession()) ; 
        /* if(user.getId().longValue() == u.getId().longValue()) {   // 修改自已的信息
          List<RoleDO> rl = Lists.newArrayList() ;
          rl.add(u.getRoleDO()) ;
          mv.addObject("roleList", rl) ;
          List<OrganizationDO> ol =Lists.newArrayList() ;
          ol.add(u.getOrganizationDO()) ;
          mv.addObject("orgList", ol);
        }else{
          setUserRole(request,mv,u) ;
          setChildOrganization(request,mv,u) ;
        }*/
        
        setUserRole(request,mv,user) ;   
        setChildOrganization(request,mv,user) ;
      }
         
      
      
      if(type >0)
         mv.addObject("type", type) ;
      return  mv ;
   }
   
   /**
    * 查询用户的角色，
    * 用户没有配角色，都查出来，
    * 如果用户配了角色，只查子角色，暂do it .
    * @param request
    * @param mv
    */
   private  void setUserRole(HttpServletRequest request,ModelAndView mv, UserDO  user){
    // UserDO  user =  SessionUtil.getCurrentUser(request.getSession()) ;
     if(user == null || user.getId() == null )
       return ;
     Result<List<RoleDO>>  rr = this.roleService.queryChildRole(user.getId()) ;
     if(rr.isSuccess() && rr.getData()!=null && !rr.getData().isEmpty() )
         mv.addObject("roleList", rr.getData()) ;
     else{
       // 本用户的角色是最底层的角色，查出来 
        RoleDO role =  this.roleService.queryRoleByUserId(user.getId()) ;
        if(role!=null){
             List<RoleDO> rL = Lists.newArrayList() ;
             rL.add(role) ;
             mv.addObject("roleList", rL) ;
        }
     }
   }
   
   private void  setChildOrganization(HttpServletRequest request,ModelAndView mv,UserDO  user){
     //UserDO  user =  SessionUtil.getCurrentUser(request.getSession()) ;
     List<OrganizationDO> orgList = null ;
     if(user ==null ||  user.getOrganizationId() ==null ){
         orgList = organizationService.queryOrganization(new OrganizationQuery()) ;
     }else
         orgList = this.organizationService.queryChildOrganizations(user.getOrganizationId()) ;
     if(orgList !=null && !orgList.isEmpty() )
         mv.addObject("orgList", orgList);
     else{
        // 此用户的组织机构是最底层的 查出来 
        Result<OrganizationDO>  or = this.organizationService.queryOrganizationById(user.getOrganizationId()) ;
        if(or.isSuccess() && or.getData()!=null){
            orgList = Lists.newArrayList() ;
            orgList.add(or.getData()) ;
            mv.addObject("orgList", orgList);
        }
     }
   }
   
   /**
    * 编辑客户信息
    * @param customerDO
    * @return
    */
   @RequestMapping(value="/doedit", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doEdit(HttpServletRequest request/*, @ModelAttribute UserDO  userDO*/ ){
     try{
        
        String params = this.getParameters(request).get("params") ;  
        if(params == null  || params.equals(""))
           return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        UserDO userDO = JsonUtils.toObject(params, UserDO.class) ;
        
        if(userDO == null )
           return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        if(userDO.getId() == null || userDO.getId() <=0)
           return JsonUtils.toJson(Result.buildError("请重新刷新页面再修改用户信息")) ;
        if(userDO.getIdCard() !=null && !userDO.getIdCard().equals("")){
          if(!IdCardUtil.verify(userDO.getIdCard()))
            return JsonUtils.toJson(Result.buildError("身份证号码不合法")) ;
       }
        
       /* UserDO  user = SessionUtil.getCurrentUser(request.getSession()) ;
        if(user.getId().longValue() == userDO.getId().longValue())
            return  JsonUtils.toJson(Result.buildError("不能修改自已的信息")) ;*/
        
         Result<Boolean>  result =this.userService.modifyUser(userDO) ;
         
         return  JsonUtils.toJson(result,true) ;
     }catch(Throwable e){
       logger.error(BaseResultCode.USER_MODIFY_USER_ERROR.getErrMsg(), e);
       return JsonUtils.toJson(Result.buildError(BaseResultCode.USER_MODIFY_USER_ERROR));
     }
   }
   
   /**
    * 跳到生成二维码页面
    * 生成二维码的方法在QRCodeMgrController中
    * @return
    */
   /*@RequestMapping("/toqrcode")
   public ModelAndView  toQRCode(){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/user/qrCodeAdd"); 
     return mv ;
   } */
   
}
